
import _ from "lodash";

var ossClient = require('../../../static/aliyun-oss-sdk.min.js');
var co = require('co');


const currentPath = window.location.protocol + '//';

//四舍五入
Number.prototype._toFixed = function (len) {
  return _.round(this, len)
}

//小数不需要四舍五入的方法
Number.prototype.floatNum = function (len) {
  var add = 0;
  var s, temp;
  var s1 = this + "";
  var start = s1.indexOf(".");
  if (start > -1 && s1.length - start > len + 1) {
    if (s1.substr(start + len + 1, 1) > 10) add = 1;
    var temp = Math.pow(10, len);
    s = Math.floor(this * temp) + add;
    return s / temp * 1;
  } else {
    return this * 1;
  }
}


/**
 *
 * @desc   判断是否为邮箱地址
 * @param  {String}  str
 * @return {Boolean}
 */
export const isEmail = function (str) {
  return /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(str);
}


/**
 *
 * @desc  判断是否为身份证号
 * @param  {String|Number} str
 * @return {Boolean}
 */
export const isIdCard = function (str) {

  return /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(str)

}

/**
 *
 * @desc   判断是否为手机号
 * @param  {String|Number} str
 * @return {Boolean}
 */

export const isPhoneNum = function isPhoneNum(str) {
  return /^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/.test(
    str
  )
}


export const getTimestamp = val => {
  // 转换时间戳
  if (val == "") {
    return "";
  }
  let date = new Date(val).getTime();
  return date;
};

export const getLocalTime = (val, type) => { // 时间戳转本地时间
  // type == 1 全部格式, type == 2 显示年月日
  var type = type || 1;
  if (val == '') {
    return ''
  }

  function add0(m) {
    return m < 10 ? '0' + m : m
  };

  function getDate(val) {
    //val是整数，否则要parseInt转换
    var time = new Date(val);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    if (type == 1) {
      return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
    } else {
      return y + '-' + add0(m) + '-' + add0(d);
    }

  }
  return getDate(val)

}



/*
 ** 时间戳转换成指定格式日期
 ** eg.
 ** dateFormat(11111111111111, 'Y年m月d日 H时i分')
 ** → "2322年02月06日 03时45分"
 */
/*
 ** 时间戳转换成指定格式日期
 ** eg.
 ** dateFormat(11111111111111, 'Y年m月d日 H时i分')
 ** → "2322年02月06日 03时45分"
 */
export const dateFormat = function (timestamp, formats) {
  // formats格式包括
  // 1. Y-m-d
  // 2. Y-m-d H:i:s
  // 3. Y年m月d日
  // 4. Y年m月d日 H时i分
  formats = formats || 'Y-m-d';

  var zero = function (value) {
    if (value < 10) {
      return '0' + value;
    }
    return value;
  };

  var myDate = timestamp ? new Date(timestamp) : new Date();

  var year = myDate.getFullYear();
  var month = zero(myDate.getMonth() + 1);
  var day = zero(myDate.getDate());

  var hour = zero(myDate.getHours());
  var minite = zero(myDate.getMinutes());
  var second = zero(myDate.getSeconds());

  return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
    return ({
      Y: year,
      m: month,
      d: day,
      H: hour,
      i: minite,
      s: second
    })[matches];
  });
};

isEmail
isPhoneNum
export const userNameTransform = function (userName) {

  if (isPhoneNum(userName)) { //手机号
    let strarr = userName.split('');
    strarr.splice(3, 4, "****");
    userName = strarr.join('');
  } else if (isEmail(userName)) { //邮箱
    let emailarr = userName.split('@')[0].split('');
    let lastEmail = userName.split('@')[1];
    let len = emailarr.length;
    if (len <= 4) {
      emailarr.splice(len - 2, len - 1, "**");
      userName = emailarr.join('') + "@" + lastEmail;
    } else {
      emailarr.splice(len - 3, len - 2, "***");
      userName = emailarr.join('') + "@" + lastEmail;
    }
  }
  return userName;
}



//  身份验证图片上传阿里云
export const uploadFile = function (fileId, pic, tips, cb) {
  var _self = this;
  var url = '';
  //添加随机数
  var random = Math.random().toString(36).substr(2);
  var time = new Date().getTime();
  var caution = document.getElementById(tips);
  caution.textContent = '上传中';
  caution.style.color = '#3b7bea'
  // var random = Math.floor(Math.random()*(100-1+1)+1);
  return ossClient.urllib.request(currentPath + window.location.host + '/nb-web/api/upload/getOssStsToKen', {
    method: 'post'
  }).then(function (result) {
    var creds = JSON.parse(result.data);
    var aliyun = creds.result.data.domain;
    var client = new ossClient.Wrapper({
      region: 'oss-cn-shenzhen',
      secure: true,
      accessKeyId: creds.result.data.accessKeyId,
      accessKeySecret: creds.result.data.accessKeySecret,
      stsToken: creds.result.data.securityToken,
      bucket: creds.result.data.bucket
    });
    var file = document.getElementById(fileId).files[0];
    var key = dateFormat(new Date(), 'y-m-d') + '-' + time + random;
    return client.multipartUpload(key, file, {

    }).then(function (res) {
      caution.textContent = '上传成功';
      caution.style.color = '#3b7bea';
      document.getElementById(pic).src = res.res.requestUrls[0].split('?')[0];//将上传图片显示在页面中
      // cb(); //事件回调
    }).catch(function (err) {
      caution.textContent = '上传失败1';
      caution.style.color = 'red'
    });


  }).catch(function (err) {
    caution.textContent = '上传失败2';
    caution.style.color = 'red'
  });
}


//
//  图片上传阿里云
export const uploadFile_bbs = function (file, cb, error) {
  //   var _self = this;
  //   var url = '';
  //添加随机数
  var random = Math.random().toString(36).substr(2);
  var time = new Date().getTime();
  //   var caution = document.getElementById(tips);
  //   caution.textContent='上传中';
  //   caution.style.color='#3b7bea'
  // var random = Math.floor(Math.random()*(100-1+1)+1);
  return ossClient.urllib.request(currentPath + window.location.host + '/nb-web/api/upload/getOssStsToKen', {
    method: 'post'
  }).then(function (result) {
    var creds = JSON.parse(result.data);
    var aliyun = creds.result.data.domain;
    var client = new ossClient.Wrapper({
      region: 'oss-cn-shenzhen',
      secure: true,
      accessKeyId: creds.result.data.accessKeyId,
      accessKeySecret: creds.result.data.accessKeySecret,
      stsToken: creds.result.data.securityToken,
      bucket: creds.result.data.bucket
    });
      var file = document.getElementById(fileId).files[0];
    var key = dateFormat(new Date(), 'Y-m-d') + '-' + time + random;
    return client.multipartUpload(key, file, {

    }).then(function (res) {
      //  caution.textContent='上传成功';
      //  caution.style.color='#3b7bea'
      //   document.getElementById(pic).src=
      console.log(res.res);
      let imgUrl = res.res.requestUrls[0].split('?')[0];
      cb(imgUrl); //事件回调
    }).catch(function (err) {
      //  caution.textContent='上传失败';
      //  caution.style.color='red'

      if (error) {
        error()
      }
      alert('上传失败')
    });
  }).catch(function (err) {
    //  caution.textContent='上传失败';
    //  caution.style.color='red'
    console.log(err)
    if (error) {
      error()
    }
    alert('上传失败')
  });
}



// 裁剪图片 上传 阿里云
export const avatar_upload = function (blob, cb) {
  var random = Math.random().toString(36).substr(2);
  var time = new Date().getTime();

  // blob转arrayBuffer
  var reader = new FileReader();
  reader.readAsArrayBuffer(blob);

  reader.onload = function (event) {
    return ossClient.urllib.request(currentPath + window.location.host + '/nb-web/api/upload/getOssStsToKen', {
      method: 'post'
    }).then((result) => {
      var creds = JSON.parse(result.data);
      var aliyun = creds.result.data.domain;
      var client = new ossClient.Wrapper({
        region: 'oss-cn-shenzhen',
        secure: true,
        accessKeyId: creds.result.data.accessKeyId,
        accessKeySecret: creds.result.data.accessKeySecret,
        stsToken: creds.result.data.securityToken,
        bucket: creds.result.data.bucket
      });

      // 文件名
      var date = new Date();
      var time = '' + date.getFullYear() + (date.getMonth() + 1) + (date.getDate());
      var storeAs = 'Uploads/file/' + time + '/' + date.getTime() + '.' + blob.type.split('/')[1];

      // arrayBuffer转Buffer
      var buffer = new ossClient.Buffer(event.target.result);

      // 上传
      client.put(storeAs, buffer).then(function (result) {
        console.log(result);
        console.log('上传成功');
        var url = result.url;
        // 拿到url 处理事件回调
        if (cb) {
          cb(url)
        }

      }).catch(function (err) {
        console.log(err);
      });
    }).catch(function (err) {
      console.log(err);
      alert('上传失败')
    });
  }
}


export function pop(val, fn) {
//动态插入
  $('#pop').remove();
  $(document.body).append('<div id="pop"></div>');
  //  $('#pop').html(val);
  var pop_style = {
    "position": "fixed",
    "top": "50%",
    "left": "50%",
    "transform": "translate(-50%,-50%)",
    "z-index": 3000000,
    "height": "42px",
    "border-radius": "4px",
    "background": "rgba(0,0,0,0.5)",
    "line-height": " 42px",
    "text-align": "center",
    "transition": "all 0.4s",
    "opacity": 1,
    "visibility": "visible",
    "color": "#fff",
    "font-size": "14",
    "padding": "0 15px",
    "white-space": "nowrap",
    "display": "none"
  }

  $("#pop").css(pop_style).html(val).animate({
    "opacity": 0.7
  }, 2000, function () {
    $(this).remove();
    if (fn) {
      fn();
    }
  });

}



// js 精确计算
export const mathService = function () {

  this.add = function (a, b) {
    var c, d, e;
    try {
      c = a.toString().split(".")[1].length;
    } catch (f) {
      c = 0;
    }
    try {
      d = b.toString().split(".")[1].length;
    } catch (f) {
      d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) + this.mul(b, e)) / e;
  }

  this.mul = function (a, b) {
    var c = 0,
      d = a.toString(),
      e = b.toString();
    try {
      c += d.split(".")[1].length;
    } catch (f) {}
    try {
      c += e.split(".")[1].length;
    } catch (f) {}
    return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
  }

  this.sub = function (a, b) {
    var c, d, e;
    try {
      c = a.toString().split(".")[1].length;
    } catch (f) {
      c = 0;
    }
    try {
      d = b.toString().split(".")[1].length;
    } catch (f) {
      d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) - this.mul(b, e)) / e;
  }

  this.div = function (a, b) {
    var c, d, e = 0,
      f = 0;
    try {
      e = a.toString().split(".")[1].length;
    } catch (g) {}
    try {
      f = b.toString().split(".")[1].length;
    } catch (g) {}
    return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), this.mul(c / d, Math.pow(10, f - e));
  }
}




// 获取语言
export const USERLANG = function () {
  var langType = "";
  var _lang = (navigator.systemLanguage ? navigator.systemLanguage : navigator.language);
  var lang = localStorage.lang

  if (lang) {
    langType = lang
  } else {
    //获取浏览器配置语言 #括号内是个运算，运算过后赋值给lang，当?前的内容为true时把?后的值赋给lang，为False时把:后的值赋给lang
    var _lang = _lang.substr(0, 2); //获取lang字符串的前两位
    if (_lang == 'zh') {
      // alert('中文浏览器');
      langType = 'CN'
    } else if (_lang == 'en') {
      // alert('英文浏览器');
      langType = 'EN'
    } else if (_lang == 'ja') {
      // alert('日文浏览器');
      langType = 'JP'
    } else {
      //  英文
      langType = 'EN'
    }
  }
  return langType;

}
